package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.ArticleTags;
import com.yupi.yuoj.service.ArticleTagsService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 文章标签关联接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/article-tags")
@Slf4j
public class ArticleTagsController {

    @Resource
    private ArticleTagsService articleTagsService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建文章标签关联
     *
     * @param articleTags
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addArticleTag(@RequestBody ArticleTags articleTags, HttpServletRequest request) {
        if (articleTags == null || articleTags.getArticle_id() == null || articleTags.getTag_id() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 检查是否已存在相同的关联
        ArticleTags existingRelation = articleTagsService.lambdaQuery()
                .eq(ArticleTags::getArticle_id, articleTags.getArticle_id())
                .eq(ArticleTags::getTag_id, articleTags.getTag_id())
                .one();
        if (existingRelation != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文章标签关联已存在");
        }
        boolean result = articleTagsService.save(articleTags);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newArticleTagId = articleTags.getId();
        return ResultUtils.success(newArticleTagId);
    }

    /**
     * 删除文章标签关联
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteArticleTag(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        ArticleTags oldArticleTag = articleTagsService.getById(id);
        ThrowUtils.throwIf(oldArticleTag == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = articleTagsService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 根据文章ID删除所有标签关联
     *
     * @param articleId
     * @param request
     * @return
     */
    @PostMapping("/delete/by-article")
    public BaseResponse<Boolean> deleteByArticleId(@RequestParam Long articleId, HttpServletRequest request) {
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = articleTagsService.lambdaUpdate()
                .eq(ArticleTags::getArticle_id, articleId)
                .remove();
        return ResultUtils.success(result);
    }

    /**
     * 根据标签ID删除所有文章关联
     *
     * @param tagId
     * @param request
     * @return
     */
    @PostMapping("/delete/by-tag")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteByTagId(@RequestParam Integer tagId, HttpServletRequest request) {
        if (tagId == null || tagId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = articleTagsService.lambdaUpdate()
                .eq(ArticleTags::getTag_id, tagId)
                .remove();
        return ResultUtils.success(result);
    }

    /**
     * 根据文章ID获取标签列表
     *
     * @param articleId
     * @return
     */
    @GetMapping("/list/by-article")
    public BaseResponse<List<ArticleTags>> getTagsByArticleId(@RequestParam Long articleId) {
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<ArticleTags> articleTagsList = articleTagsService.lambdaQuery()
                .eq(ArticleTags::getArticle_id, articleId)
                .orderByAsc(ArticleTags::getCreated_at)
                .list();
        return ResultUtils.success(articleTagsList);
    }

    /**
     * 根据标签ID获取文章列表
     *
     * @param tagId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/by-tag")
    public BaseResponse<Page<ArticleTags>> getArticlesByTagId(
            @RequestParam Integer tagId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        if (tagId == null || tagId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<ArticleTags> articleTagsPage = articleTagsService.lambdaQuery()
                .eq(ArticleTags::getTag_id, tagId)
                .orderByDesc(ArticleTags::getCreated_at)
                .page(new Page<>(current, size));
        return ResultUtils.success(articleTagsPage);
    }

    /**
     * 分页获取文章标签关联列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ArticleTags>> listArticleTagByPage(@RequestParam long current, @RequestParam long size) {
        Page<ArticleTags> articleTagPage = articleTagsService.page(new Page<>(current, size));
        return ResultUtils.success(articleTagPage);
    }

    /**
     * 批量添加文章标签关联
     *
     * @param articleId
     * @param tagIds
     * @param request
     * @return
     */
    @PostMapping("/batch/add")
    public BaseResponse<Boolean> batchAddArticleTags(
            @RequestParam Long articleId,
            @RequestParam List<Integer> tagIds,
            HttpServletRequest request) {
        if (articleId == null || articleId <= 0 || tagIds == null || tagIds.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        // 先删除该文章的所有标签关联
        articleTagsService.lambdaUpdate()
                .eq(ArticleTags::getArticle_id, articleId)
                .remove();
        
        // 批量添加新的标签关联
        for (Integer tagId : tagIds) {
            ArticleTags articleTag = new ArticleTags();
            articleTag.setArticle_id(articleId);
            articleTag.setTag_id(tagId);
            articleTagsService.save(articleTag);
        }
        
        return ResultUtils.success(true);
    }

}